package com.achievo.know.domain.infra.hibernate;

import java.util.List;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.achievo.know.domain.FriendLink;
import com.achievo.know.domain.FriendLinkRepository;
import com.achievo.know.domain.FriendLink.LinkType;
import com.dayatang.spring.repository.BaseEntityRepositoryHibernateSpring;

@Repository
public class FriendLinkRepositoryImpl extends BaseEntityRepositoryHibernateSpring<FriendLink,Long> implements FriendLinkRepository {

	public FriendLinkRepositoryImpl() {
		super(FriendLink.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<FriendLink> findLinks(LinkType in) {
		DetachedCriteria c=DetachedCriteria.forClass(FriendLink.class);
		c.add(Restrictions.eq("type",in));
		c.addOrder(Order.desc("order"));
		return getHibernateTemplate().findByCriteria(c);
	}

	@Override
	public FriendLink getUp(FriendLink link) {
		DetachedCriteria c=DetachedCriteria.forClass(FriendLink.class);
		c.add(Restrictions.eq("type",link.getType()));
		c.addOrder(Order.asc("order"));
		c.add(Restrictions.gt("order", link.getOrder()));
		getHibernateTemplate().setFetchSize(1);
		List<FriendLink> list= getHibernateTemplate().findByCriteria(c);
		if(list.size()>0)
			return list.get(0);
		return null;
	}

	@Override
	public FriendLink getDown(FriendLink link) {
		DetachedCriteria c=DetachedCriteria.forClass(FriendLink.class);
		c.add(Restrictions.eq("type",link.getType()));
		c.addOrder(Order.desc("order"));
		c.add(Restrictions.lt("order", link.getOrder()));
		getHibernateTemplate().setFetchSize(1);
		List<FriendLink> list= getHibernateTemplate().findByCriteria(c);
		if(list.size()>0)
			return list.get(0);
		return null;
	}

}
